import NProgress from '@/utils/nprogress'
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'

// 自动导入views目录下的Vue文件
const viewsModules = import.meta.glob('../views/**/*.vue')

// 路由生成函数
function generateRoutes(): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []
  const routeMap = new Map<string, RouteRecordRaw>()

  // 处理所有Vue文件
  for (const path in viewsModules) {
    const module = viewsModules[path] as any
    const component = module.default || module

    // 从路径中提取路由信息
    const relativePath = path.replace('../views/', '').replace('.vue', '')
    const pathSegments = relativePath.split('/')

    // 生成路由路径
    let routePath = ''
    let routeName = ''

    if (pathSegments.length === 1) {
      // 根目录下的文件
      const fileName = pathSegments[0]
      if (fileName === 'index') {
        routePath = '/'
        routeName = 'index'
      } else if (fileName === '404') {
        routePath = '/:pathMatch(.*)*'
        routeName = 'not-found'
      } else {
        routePath = `/${fileName}`
        routeName = fileName
      }
    } else {
      // 子目录下的文件
      const folderName = pathSegments[0]
      const fileName = pathSegments[1]

      if (fileName === 'index') {
        // index文件作为父路由
        routePath = `/${folderName}`
        routeName = folderName
      } else {
        // 其他文件作为子路由
        routePath = `/${folderName}/${fileName}`
        routeName = `${folderName}-${fileName}`
      }
    }

    // 创建路由对象
    const route: RouteRecordRaw = {
      path: routePath,
      name: routeName,
      component: component,
      meta: {
        title: component.name || routeName
      }
    }

    // 处理嵌套路由
    if (pathSegments.length > 1) {
      const folderName = pathSegments[0]
      const fileName = pathSegments[1]

      if (fileName === 'index') {
        // 这是父路由的index文件
        routeMap.set(folderName, route)
        routes.push(route)
      } else {
        // 这是子路由文件
        const parentRoute = routeMap.get(folderName)

        if (parentRoute) {
          // 如果父路由已存在，添加子路由
          if (!parentRoute.children) {
            parentRoute.children = []
          }
          parentRoute.children.push(route)
        } else {
          // 如果父路由不存在，创建父路由并添加子路由
          const parentRoute: RouteRecordRaw = {
            path: `/${folderName}`,
            name: folderName,
            component: () => import(`../views/${folderName}/index.vue`),
            children: [route]
          }
          routeMap.set(folderName, parentRoute)
          routes.push(parentRoute)
        }
      }
    } else {
      // 这是根路由
      routes.push(route)
    }
  }

  return routes
}

const routes = generateRoutes()

const router = createRouter({
  history: createWebHashHistory(),
  routes: routes,
  strict: false,
})

router.beforeEach((to, from) => {
  NProgress.start()
})

router.afterEach((to, from) => {
  NProgress.done()
})

router.afterEach(() => { })

export default router
